import requests
from flask import current_app
from common.error_handler import HttpError


def make_request_body(server_name, data_dict: dict):
    """
    :param server_name: 服务名, str类型, 在settings中配置的服务域名
    :param data_dict: 接口的请求参数字典，dict类型
    # 请求传参通过 params、data、json 区分使用 url 传参、key-value传参、json传参
    :return: 返回 request body
    """
    # 获取配置中的服务器域名，拼接path
    url = current_app.config[server_name] + data_dict.get("path", "")
    method = data_dict.get("method", "get")
    headers = data_dict.get("headers", {})
    params = data_dict.get("params", {})
    data = data_dict.get("data", {})
    json = data_dict.get("json", {})

    request_body = {
        "url": url,
        "method": method,
        "headers": headers,
        "params": params,
        "data": data,
        "json": json
    }
    return request_body


def send_request(request_body, **kwargs):
    """
    :param request_body 请求数据
    :param kwargs: 扩展支持 files 上传文件、proxy 代理等
    :return:
    """
    url = request_body["url"]
    method = request_body["method"]
    headers = request_body["headers"]
    params = request_body["params"]
    data = request_body["data"]
    json = request_body["json"]

    if not url.startswith("http://") and not url.startswith("https://"):
        raise HttpError("请求url缺少协议名")
    if method.lower() not in ("get", "post", "put", "delete"):
        raise HttpError(f"暂不支持请求方法 - {method} - 可后续扩展")

    data_log = ""
    if params:
        data_log = f"params: {params}"
    if data:
        data_log = f"data: {data}"
    if json:
        data_log = f"json: {json}"
    if kwargs:
        data_log += f"\nkwargs: {kwargs}"

    current_app.logger.info("\n----------   request  info  ----------\n"
                            f"url: {url}\n"
                            f"method: {method}\n"
                            f"headers: {headers}\n"
                            f"{data_log}"
                            )

    try:
        response = requests.request(**request_body, timeout=30, **kwargs)
    except Exception as e:
        current_app.logger.warning(f"请求发生异常!!!")
        raise HttpError(e)

    if response.status_code == 200:
        current_app.logger.info("\n----------   response  info  ----------\n"
                                f"status: {response.status_code}\n"
                                f"headers: {response.headers}\n"
                                f"body: {response.text}")
    else:
        current_app.logger.warning(f"请求失败!!! 响应码不为200, 状态码为: {response.status_code}")
        current_app.logger.warning("\n----------   response  info  ----------\n"
                                   f"text: {response.text}\n"
                                   f"raw: {response.raw}")
        raise HttpError("响应码不为200")
    try:
        # 返回为字典类型
        return response.json()
    except requests.exceptions.JSONDecodeError:
        current_app.logger.warning("响应参数不为json，返回响应 response对象")
        return response


